import { store } from "@/store";
import { defineStore } from 'pinia';
import { setAccessToken, setRefreshToken, getRefreshToken } from "@/utils/auth";
import AuthAPI  from '@/api/auth.api.ts'

export const useUserStore = defineStore('user', () =>{

  /**
   * 刷新 token
   */
  function refreshToken()
  {
    const refreshToken = getRefreshToken();
    return new Promise<void>((resolve, reject) => {
      AuthAPI.refreshToken(refreshToken)
        .then((data) => {
          const { accessToken, refreshToken } = data;
          setAccessToken(accessToken);
          setRefreshToken(refreshToken);
          resolve();
        })
        .catch((error) => {
          console.log(" refreshToken  刷新失败", error);
          reject(error);
        });
    });
  }

  return {
    refreshToken,
  };

});

export function useUserStoreHook() {
  return useUserStore(store);
}

